package com.sunshine.student_register.ui.activity.register;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;

import com.sunshine.student_register.database.StudentRegisterRepository;
import com.sunshine.student_register.database.student.StudentEntity;

/**
 * @author sunshine
 * @date 2020/5/30
 * 用户注册viewModel
 */
public class UserRegisterViewModel extends AndroidViewModel {

    private SharedPreferences sp;
    private StudentRegisterRepository repository;
    private int userId;

    public UserRegisterViewModel(@NonNull Application application) {
        super(application);

        sp = getApplication().getSharedPreferences("app_setting", Context.MODE_PRIVATE);
        repository = new StudentRegisterRepository(getApplication());
    }

    boolean hasThisUser(String userId){
        try {
            this.userId = Integer.parseInt(userId);
            return null != repository.getStudent(this.userId);
        }catch (Exception e){
            return true;
        }

    }

    void insertStudent(StudentEntity studentEntity){
        repository.insertStudent(studentEntity);
        sp.edit().putInt("user_id", userId).apply();
    }
}
